package org.jeecg.modules.payment.strategy.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.JacksonUtil;
import org.jeecg.modules.payment.bo.IcBcPayChannel;
import org.jeecg.modules.payment.bo.PaymentParams;
import org.jeecg.modules.payment.bo.RefundParams;
import org.jeecg.modules.payment.strategy.IPaymentService;
import org.jeecg.modules.payment.util.IcbcApiUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;


/**
 * @Description: 工商银行支付渠道
 * @Author: sean
 * @Date:   2024-09-26
 * @Version: V1.0
 */
@Slf4j
public class ICBCPaymentService implements IPaymentService {
    private IcBcPayChannel payChannel;

    public ICBCPaymentService(String payConfig) {
        this.payChannel = JacksonUtil.toJavaObject(payConfig,  IcBcPayChannel.class);
    }

    @Override
    public JsonNode payment(PaymentParams params) throws JeecgBootException {
        String notifyUrl = PAYMENT_NOTIFY_URL
                + "/" + params.getBizType()
                + "/" + params.getPayChannel()
                + "/" + params.getPayWay()
                + "/" + TenantContext.getTenant();
        log.info("支付回调接口-------------:{}", notifyUrl);
        params.setPaymentNotifyUrl(notifyUrl);
        JsonNode jsonNode = IcbcApiUtil.createOrder(params, this.payChannel);
        String wxDataPackageStr = jsonNode.get("wx_data_package").asText();
        JsonNode wxDataPackage = JacksonUtil.parseJSONObject(wxDataPackageStr);
        ObjectNode result = JacksonUtil.newJSONObject();
        result.put("appid", wxDataPackage.get("appid").asText());  //appid
        result.put("timestamp", wxDataPackage.get("timestamp").asText()); //时间戳
        result.put("nonce", wxDataPackage.get("noncestr").asText()); //随机字符串
        result.put("package", wxDataPackage.get("package").asText()); //prepay_id 参数值
        result.put("signType", wxDataPackage.get("signType").asText()); //签名类型
        result.put("paySign", wxDataPackage.get("sign").asText()); // 签名
        return result;
    }

    @Override
    public JsonNode payCallBack(HttpServletRequest request, String payWay, String tenantId) throws JeecgBootException {
        String bizContent = request.getParameter("biz_content");
        log.info("bizContent===={}", bizContent);
        JsonNode content = JacksonUtil.toJSON(bizContent);
        //我们的订单编号
        String orderCode = content.get("out_trade_no").asText();
        //订单金额(单位分)
        Long totalFee = content.get("total_amt").asLong();
        //第三方订单流水号
        String transactionId = content.get("order_id").asText();
        //返回码
        String returnCode = content.get("return_code").asText();
        //消息号
        String msgId = content.get("msg_id").asText();
        log.info("订单{}【工商银行】微信回调签名认证成功", orderCode);
        ObjectNode params = JacksonUtil.newJSONObject();
        params.put("msgId", msgId)
                .put("returnCode", returnCode)
                .put("payCode", orderCode)
                .put("otherCode", transactionId)
                .put("payAmount", BigDecimal.valueOf(totalFee).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP));
        return params;
    }

    @Override
    public JsonNode refund(RefundParams params) throws JeecgBootException {
//        String json = WechatChannelUtil.refund(params, this.payChannel);
//        return JacksonUtils.toObj(json);
        return null;
    }

    @Override
    public ObjectNode refundCallBack(JsonNode params) throws JeecgBootException {
        return null;
    }

    @Override
    public void callbackResponse(HttpServletResponse response, JsonNode params, boolean result) {
        String msgId = params.get("msgId").asText();
        String results =  IcbcApiUtil.notifyStr(result, msgId, this.payChannel);
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(results);
        } catch (Exception e) {
            log.error("【工商银行】微信支付回调处理失败,请检查原因!!!,{}", e.getMessage());
        } finally {
            out.flush();
            out.close();
        }
    }
}
